package com.ruoyi.project.system.service.impl;

import java.util.*;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.HttpUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.domain.SysBank;
import com.ruoyi.project.system.domain.SysCompany;
import com.ruoyi.project.system.domain.SysExchange;
import com.ruoyi.project.system.mapper.SysBankMapper;
import com.ruoyi.project.system.mapper.SysCompanyMapper;
import com.ruoyi.project.system.service.ISysCompanyService;
import com.ruoyi.project.system.service.ISysDictDataService;
import com.ruoyi.project.system.service.ISysExchangeService;
import com.ruoyi.project.tool.swagger.UserController.SignUtil;
import okhttp3.HttpUrl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.project.system.mapper.SysReceiveMapper;
import com.ruoyi.project.system.domain.SysReceive;
import com.ruoyi.project.system.service.ISysReceiveService;
import org.springframework.transaction.annotation.Transactional;
import test.util.SequenceUtils;

/**
 * 领取Service业务层处理
 *
 * @author theme
 * @date 2021-04-20
 */
@Service
public class SysReceiveServiceImpl implements ISysReceiveService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private SysReceiveMapper sysReceiveMapper;

    @Autowired
    private ISysExchangeService sysExchangeService;

    @Autowired
    private SysCompanyMapper sysCompanyMapper;

    @Autowired
    private SysBankMapper sysBankMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private ISysCompanyService sysCompanyService;

    /**
     * 查询领取
     *
     * @param receiveId 领取ID
     * @return 领取
     */
    @Override
    public SysReceive selectSysReceiveById(Long receiveId) {
        return sysReceiveMapper.selectSysReceiveById(receiveId);
    }

    /**
     * 查询领取列表
     *
     * @param sysReceive 领取
     * @return 领取
     */
    @Override
    public List<SysReceive> selectSysReceiveList(SysReceive sysReceive) {
        return sysReceiveMapper.selectSysReceiveList(sysReceive);
    }

    /**
     * 新增领取
     *
     * @param sysReceive 领取
     * @return 结果
     */
    @Override
    @Transactional
    public int insertSysReceive(SysReceive sysReceive) {
        sysReceive.setCreateTime(DateUtils.getNowDate());
        return sysReceiveMapper.insertSysReceive(sysReceive);
    }

    @Override
    public AjaxResult insertSysReceiveData(SysReceive sysReceive) {
        String date = SequenceUtils.getCurentDate();
        String key = "serial.gooods:" + date;
        //** 自增 *//*
        long sequence = redisTemplate.opsForValue().increment(key);
        String orderNo = date + SequenceUtils.getSequence(sequence);
        sysReceive.setOrders(orderNo);
        sysReceive.setStatus("0");
        sysReceive.setCreateTime(DateUtils.getNowDate());
        SysBank sysBank = null;
        if (null == sysBank) {
            return AjaxResult.error("操作人员失效!");
        }
        sysReceive.setNickName(sysBank.getUserName());
        sysReceive.setImg(sysBank.getBranch());
        sysReceive.setOutlets(sysBank.getOutlets());
        String typeName = dictDataService.selectDictLabel("sys_bussiness_type", sysReceive.getType());
        if (StringUtils.isNotEmpty(typeName)) {
            sysReceive.setTypeName(typeName);
        }
        sysReceiveMapper.insertSysReceive(sysReceive);
        String openid = sysReceive.getOpenId();
        String url = "https://api.mch.weixin.qq.com/v3/marketing/favor/users/" + openid + "/coupons";
        JSONObject data = new JSONObject();
        data.put("out_request_no", orderNo);//订单号
        data.put("stock_id", sysReceive.getType());//代金券批次id也就是商品编号
        data.put("appid", wxMaService.getWxMaConfig().getAppid());
        data.put("stock_creator_mchid", "1605617216");//商户号
        SignUtil signUtil = new SignUtil();
        JSONObject result = null;
        try {
            result = new JSONObject();
            result.put("coupon_id", UUID.randomUUID());
//            result = HttpUtil.doPost(url, data, signUtil.getToken("POST", HttpUrl.parse(url), data.toJSONString()));
        } catch (Exception e) {
            System.out.println(result.toJSONString());
            return AjaxResult.error("调用微信失败");
        }
        System.out.println(result.toJSONString());
        if (result.containsKey("coupon_id")) {
            sysReceive.setStatus("1");
            sysReceive.setRemark(result.getString("coupon_id"));
            sysReceive.setUsed("SENDED");
            sysReceive.setUpdateTime(DateUtils.getNowDate());
            int flag = sysReceiveMapper.updateSysReceive(sysReceive);
            if (flag == 1) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("dictCode", sysReceive.getType());
                jsonObject.put("openId", openid);
                jsonObject.put("phone", sysReceive.getPhone());
                jsonObject.put("couponId", sysReceive.getRemark());
                AsyncManager.me().execute(AsyncFactory.sendPayment(rabbitTemplate, jsonObject));

                return AjaxResult.success("领取成功!");
            }
        }
        return AjaxResult.error(result.getString("message"));
    }

    @Override
    @Transactional
    public AjaxResult insertSysReceiveDataDisable(SysReceive sysReceive) {
        SysCompany company = sysCompanyMapper.selectSysCompanyById(sysReceive.getCompanyId());
        Date date1 = new Date();
        if (date1.after(company.getFinishTime())) {
            return AjaxResult.error("活动已结束");
        }
        if ( date1.before(company.getStartTime())) {
            return AjaxResult.error("活动暂未开始");
        }
        SysExchange sysExchange = new SysExchange();
        sysExchange.setCompanyId(sysReceive.getCompanyId());
        sysExchange.setCode(sysReceive.getSecret());
        List<SysExchange> lists = sysExchangeService.selectSysExchangeList(sysExchange);
        if (lists.isEmpty()) {
            return AjaxResult.error("密语错误~");
        }
        SysExchange exchange = lists.get(0);
        if (exchange.getDeleted().intValue() != 0) {
            return AjaxResult.error("兑换码暂未启用!");
        }
        if (exchange.getNum() <= 0) {
            return AjaxResult.error("哎呀，被抢光啦，领取要趁早哦~");
        }
        sysReceive.setTypeName(exchange.getTypeName());
        sysReceive.setType(exchange.getType());
        String date = SequenceUtils.getCurentDate();
        String key = "serial.gswb.gooods:" + date;
        //** 自增 *//*
        long sequence = redisTemplate.opsForValue().increment(key);
        String orderNo = date + SequenceUtils.getSequence(sequence);
        sysReceive.setOrders(orderNo);
        sysReceive.setStatus("0");
        sysReceive.setCreateTime(DateUtils.getNowDate());
        sysReceive.setOutlets(exchange.getMoney());
        sysReceive.setNickName(company.getName());
        sysReceiveMapper.insertSysReceive(sysReceive);
        exchange.setNum(exchange.getNum()-1);
        sysExchangeService.updateSysExchange(exchange);
        String openid = sysReceive.getOpenId();
        String url = "https://api.mch.weixin.qq.com/v3/marketing/favor/users/" + openid + "/coupons";
        JSONObject data = new JSONObject();
        data.put("out_request_no", orderNo);//订单号
        data.put("stock_id", sysReceive.getType());//代金券批次id也就是商品编号
        data.put("appid", wxMaService.getWxMaConfig().getAppid());
        data.put("stock_creator_mchid", "1605617216");//商户号
        SignUtil signUtil = new SignUtil();
        JSONObject result = null;
        try {
            result = new JSONObject();
//            result.put("coupon_id", UUID.randomUUID());
            result = HttpUtil.doPost(url, data, signUtil.getToken("POST", HttpUrl.parse(url), data.toJSONString()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("系统错误,请联系客服!");
        }
        int flag = 0;
        if (result.containsKey("coupon_id")) {
            sysReceive.setStatus("1");
            sysReceive.setRemark(result.getString("coupon_id"));
            sysReceive.setUsed("SENDED");
            sysReceive.setUpdateTime(DateUtils.getNowDate());
            flag = sysReceiveMapper.updateSysReceive(sysReceive);
            if (flag > 0 ) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("dictCode", sysReceive.getType());
                jsonObject.put("openId", openid);
                jsonObject.put("phone", sysReceive.getPhone());
                jsonObject.put("couponId", sysReceive.getRemark());
                AsyncManager.me().execute(AsyncFactory.sendPayment(rabbitTemplate, jsonObject));
                return AjaxResult.success(result.getString("message"));
            }
            return AjaxResult.success("领取成功!");
        } else {
            if(result.containsValue("FREQUENCY_LIMIT_EXCEED")){
                sysReceive.setReason(result.getString("message"));
                sysReceiveMapper.updateSysReceive(sysReceive);
                return AjaxResult.error(result.getString("message"));
            }else{
                throw new CustomException(result.getString("message"));
            }
        }
    }

    /**
     * 修改领取
     *
     * @param sysReceive 领取
     * @return 结果
     */
    @Override
    public int updateSysReceive(SysReceive sysReceive) {
        return sysReceiveMapper.updateSysReceive(sysReceive);
    }

    /**
     * 批量删除领取
     *
     * @param receiveIds 需要删除的领取ID
     * @return 结果
     */
    @Override
    public int deleteSysReceiveByIds(Long[] receiveIds) {
        return sysReceiveMapper.deleteSysReceiveByIds(receiveIds);
    }

    /**
     * 删除领取信息
     *
     * @param receiveId 领取ID
     * @return 结果
     */
    @Override
    public int deleteSysReceiveById(Long receiveId) {
        return sysReceiveMapper.deleteSysReceiveById(receiveId);
    }

    @Override
    public AjaxResult valid(SysReceive sysReceive, Boolean flag) {
        //兑换码已使用
        if (flag) {
            SysReceive queryss = new SysReceive();
            queryss.setOpenId(sysReceive.getOpenId());
            if(null!=sysReceive.getCompanyId()){
                SysCompany company=sysCompanyService.selectSysCompanyById(sysReceive.getCompanyId());
                if(null!=company){
                   queryss.setNickName(company.getName());
                }
            }
            List<SysReceive> listsss = sysReceiveMapper.selectSysReceiveList(queryss);
            if (!listsss.isEmpty()) {
                return AjaxResult.error("请勿重复领取!");
            }
        }
        return AjaxResult.success();
    }

    @Override
    public int updateSysReceiveData(SysReceive sysReceive) {
        return sysReceiveMapper.updateSysReceive(sysReceive);
    }


    /**
     * 设置核销回调地址
     *
     * @param args
     */
    public static void main(String[] args) {
       /* String url = "https://api.mch.weixin.qq.com/v3/marketing/favor/callbacks";
        JSONObject data = new JSONObject();
        data.put("mchid", "1605617216");
        data.put("notify_url", "https://adminpay.jszechao.com/activity/mobileUser/callback");//代金券批次id也就是商品编号
        data.put("switch", true);
        SignUtil signUtil = new SignUtil();
        JSONObject result = null;
        try {
            result = HttpUtil.doPost(url, data, signUtil.getToken("POST", HttpUrl.parse(url), data.toJSONString()));
        } catch (Exception e) {
            System.out.println(result.toJSONString());
        }
        System.out.println(result.toJSONString());*/
    }


    @Override
    public AjaxResult validDisable(SysReceive sysReceive, Boolean flag) {
        //二维码已使用
        if (flag) {
            SysReceive queryss = new SysReceive();
            queryss.setSecret(sysReceive.getSecret());
            List<SysReceive> listsss = sysReceiveMapper.selectSysReceiveList(queryss);
            if (!listsss.isEmpty()) {
                return AjaxResult.error("二维码已使用!");
            }
        }
        //每个手机号每个类型只能获取一次
        SysReceive querys = new SysReceive();
        querys.setStatus("1");
        querys.setType(sysReceive.getType());
        querys.setPhone(sysReceive.getPhone());
        List<SysReceive> listss = sysReceiveMapper.selectSysReceiveList(querys);
        if (!listss.isEmpty()) {
            return AjaxResult.error("该手机号已领取同业务的立减金");
        }
        //每个openId每个类型只能获取一次
        SysReceive query = new SysReceive();
        query.setStatus("1");
        query.setType(sysReceive.getType());
        query.setOpenId(sysReceive.getOpenId());
        List<SysReceive> lists = sysReceiveMapper.selectSysReceiveList(query);
        if (!lists.isEmpty()) {
            return AjaxResult.error("该微信用户已领取同业务的立减金");
        }
        return AjaxResult.success();
    }

}
